package com.coalmine.api.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.coalmine.api.annotation.LoginRequired;;
import com.coalmine.api.domain.ApiApprove;
import com.coalmine.api.domain.ApiConfig;
import com.coalmine.api.domain.ApiToken;
import com.coalmine.api.domain.req.ApplyResourceReqVO;
import com.coalmine.api.enums.EApproveStatus;
import com.coalmine.api.service.*;
import com.coalmine.common.constant.HttpStatus;
import com.coalmine.common.core.controller.BaseController;
import com.coalmine.common.core.domain.AjaxResult;
import com.coalmine.common.core.page.TableDataInfo;

import com.coalmine.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 公共资源服务目录接口
 *
 * @author 尚郑
 * @since 2022-06-02
 */
@Slf4j
@Api(tags = "API-资源服务目录接口")
@RestController
@RequestMapping("/api/resources")
public class ApiResourcesController extends BaseController {

    @Autowired
    private IApiResourceService resourceService;

    @Autowired
    private IApiApproveService apiApproveService;

    @Autowired
    private IApiTokenService tokenService;

    @Value("${datamanage.api.context}")
    String apiContext;

    @Autowired
    private HttpServletRequest request;


    // TODO 已过期，请使用/api/token/login
    @Deprecated
    @PostMapping("/login")
    @ApiOperation("登录")
    AjaxResult login(ApiToken apiToken) {
        // 参数校验
        if (StrUtil.isBlank(apiToken.getName()) && StrUtil.isBlank(apiToken.getPassword())) {
            return AjaxResult.error(HttpStatus.BAD_REQUEST, "请输入用户名密码！");
        }
        // 校验用户名密码是否正确
        ApiToken token = resourceService.getToken(apiToken.getName(), apiToken.getPassword());
        if (ObjectUtil.isNull(token)) {
            return AjaxResult.error("未找到用户信息,用户名密码错误！");
        }
        // 存在把tokenId返回
        return AjaxResult.success(token.getId());
    }
    @GetMapping("/index")
    @ApiOperation("首页")
    @LoginRequired(required = true)
    AjaxResult index() {
        // 查询所有api分组
        List<Map> apiGroupList = resourceService.getAllGroup();
        if (CollUtil.isEmpty(apiGroupList)) {
            return AjaxResult.error("暂无发布资源");
        }
        Map<String, Object> map = resourceService.getIndex(apiGroupList);
        // 查询最热资源
        return AjaxResult.success(map);
    }
    @PostMapping("/info")
    @ApiOperation("获取信息资源")
    @LoginRequired(required = true)
    AjaxResult info() {
        startPage();
        // 查询所有api分组
        List<Map> apiGroupList = resourceService.getAllGroup();
        if (CollUtil.isEmpty(apiGroupList)) {
            return AjaxResult.error("暂无发布资源");
        }
        Map<String, Object> map = resourceService.getInfo(apiGroupList);
        String searchCount = resourceService.searchResourceCount();
//        TableDataInfo dataTable = getDataTable(search);
//        List<?> rows = dataTable.getRows();
//          long total = dataTable.getTotal();
//        map.put("rows", rows);
          map.put("total", searchCount);
        // 查询最热资源
        return AjaxResult.success(map);
    }
    @PostMapping("/getApi")
    @ApiOperation("获得信息资源详情")
    @LoginRequired(required = true)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "关键字", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "apiId", value = "表字段主键列名", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "groupId", value = "api分组id", dataType = "String", dataTypeClass = String.class)
    })
   public  AjaxResult getApi(String name, String apiId, String groupId) {
        startPage();
        List<Map> search = resourceService.searchResource(name, apiId, groupId);
        TableDataInfo dataTable = getDataTable(search);
        List<?> rows = dataTable.getRows();
        long total = dataTable.getTotal();
        Map<String, Object> map = new HashMap<>();
        map.put("rows", rows);
        map.put("total", total);
        // 查询最热资源
        return AjaxResult.success(map);
    }
    @GetMapping("/detail")
    @ApiOperation("资源详情")
    @LoginRequired(required = true)
    AjaxResult detail(String id) {
        if (StrUtil.isBlank(id)){
            return AjaxResult.error(HttpStatus.BAD_REQUEST, "资源信息异常请联系管理员!");
        }
        // 查询资源信息
        ApiConfig apiConfig = resourceService.getById(id);
        if (ObjectUtil.isNull(apiConfig)){
            return AjaxResult.error(HttpStatus.BAD_REQUEST, "资源信息异常请联系管理员!");
        }
        Map<String,Object> map = resourceService.getDetail(apiConfig,request);
        return AjaxResult.success(map);
    }
    @PostMapping("/apply")
    @ApiOperation("申请资源")
    @LoginRequired(required = true)
    AjaxResult apply(@Valid @RequestBody ApplyResourceReqVO reqVO) {
        // 获取tokenId
        String tokenId = request.getHeader("id");
        List<ApiApprove> apiApproveList = apiApproveService.listByApiUser(reqVO.getApiId(), tokenId);
        if (apiApproveList.size() > 0) {
            int pendingSize = apiApproveList.stream()
                    .filter(s -> s.getApproveType() == EApproveStatus.PENDING.getCode())
                    .collect(Collectors.toList()).size();
            if (pendingSize > 0) {
                return AjaxResult.error("审批中，请勿重复申请");
            }
            boolean exist = false;
            for (ApiApprove approve: apiApproveList) {
                if (EApproveStatus.APPROVED.getCode() == approve.getApproveType()
                        && !tokenService.checkTokenExpire(approve.getTokenId())) {
                    exist = true;
                    break;
                }
            }
            if (exist) {
                return AjaxResult.error("已通过且token未过期，请勿重复申请");
            }
            return toAjax(resourceService.apply(reqVO.getApplyReason(), reqVO.getGroupId(), tokenId, reqVO.getApiId()));
        }
        return toAjax(resourceService.apply(reqVO.getApplyReason(), reqVO.getGroupId(), tokenId, reqVO.getApiId()));
    }
}
